package com.rxt.thermopro.ui.dialog

import android.app.Dialog
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.rxt.thermopro.R
import com.rxt.thermopro.app.AppContext
import com.rxt.thermopro.app.LocalDataDao
import com.rxt.thermopro.ex.is24HourStyle
import java.util.*

class AlarmDialog : DialogFragment() {

    private lateinit var contentView: View
    private var isShow = false
    private var mScreenDensity = 0f
    private var mScreenHeight = 0
    private var mScreenWidth = 0
    private val mHandler = Handler(Looper.getMainLooper())
    private lateinit var viewOk: TextView

    //    private lateinit var viewAlarms: TextView
    private lateinit var timeView: TextView
    private lateinit var alarmNum: TextView
    private lateinit var profileName: TextView
    private lateinit var alarmText: TextView
    private var mAddress = ""

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireActivity())

        contentView = View.inflate(requireContext(), R.layout.dialog_alarm, null)
        initListener()

        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(contentView)
        dialog.setCanceledOnTouchOutside(false)

        val displayMetrics = DisplayMetrics()
        requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics)
        mScreenDensity = displayMetrics.density
        mScreenHeight = displayMetrics.heightPixels
        mScreenWidth = displayMetrics.widthPixels

        isCancelable = true
        val window: Window? = dialog.window
        if (window != null) {
            window.setBackgroundDrawable(ColorDrawable(resources.getColor(android.R.color.transparent)))
            window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            val lp: WindowManager.LayoutParams = window.attributes
            lp.gravity = Gravity.CENTER
            lp.width = mScreenWidth / 4 * 3
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT
            window.attributes = lp
        }
        return dialog
    }

    private fun initListener() {
        viewOk = contentView.findViewById(R.id.viewOk)
//        viewAlarms = contentView.findViewById(R.id.viewAlarms)
        timeView = contentView.findViewById(R.id.timeView)
        alarmNum = contentView.findViewById(R.id.alarmNum)
        profileName = contentView.findViewById(R.id.profileName)
        alarmText = contentView.findViewById(R.id.alarmText)

//        viewAlarms.setOnClickListener {
//            hideDialog()
////            AppContext.get().stopAlarm()
//        }

        viewOk.setOnClickListener {
            hideDialog()
//            AppContext.get().stopAlarm()
        }


        val calendar: Calendar = Calendar.getInstance()
        calendar.time = Date()
        val h1 = calendar.get(Calendar.HOUR)
        val h2 = calendar.get(Calendar.HOUR_OF_DAY)
        val m = calendar.get(Calendar.MINUTE)
        val mStr = if (m > 9) m.toString() else "0$m"

        if (is24HourStyle(requireContext())) {
            timeView.text = "$h2:$mStr"
        } else {
            if (h2 > 12) {
                timeView.text = "$h1:$mStr PM"
            } else {
                timeView.text = "$h1:$mStr AM"
            }
        }
    }

    private var currentPosition = -1
    fun setAlarmNum(num: String, address: String) {
        mAddress = address
        currentPosition = num.toIntOrNull() ?: -1
        mHandler.postDelayed({
            alarmNum.text = num
            when (num) {
                "1" -> {
                    profileName.text = LocalDataDao.INSTANCE.getProfile1(address).name
                    alarmText.text = LocalDataDao.INSTANCE.getAlarmText1(address)
                }
                "2" -> {
                    profileName.text = LocalDataDao.INSTANCE.getProfile2(address).name
                    alarmText.text = LocalDataDao.INSTANCE.getAlarmText2(address)
                }
                "3" -> {
                    profileName.text = LocalDataDao.INSTANCE.getProfile3(address).name
                    alarmText.text = LocalDataDao.INSTANCE.getAlarmText3(address)
                }
                "4" -> {
                    profileName.text = LocalDataDao.INSTANCE.getProfile4(address).name
                    alarmText.text = LocalDataDao.INSTANCE.getAlarmText4(address)
                }
            }
        }, 600)
    }

    fun showDialog(fragmentManager: FragmentManager) {
        try {
            if (!isShow) {
                this.show(fragmentManager, "TAG")
                isShow = true
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("123->", "showDialog Exception $e")
        }
    }

    fun hideDialog() {
        if (isShow) {
            dismiss()
            isShow = false
        }
    }

    override fun dismiss() {
        super.dismiss()
        if (currentPosition!=-1){
            AppContext.get().stopAlarm(currentPosition - 1, mAddress)
        }
    }

    override fun onResume() {
        super.onResume()
        isShow = true
    }

    override fun onPause() {
        super.onPause()
        isShow = false
    }

    override fun show(manager: FragmentManager, tag: String?) {
        val ft = manager.beginTransaction()
        ft.add(this, tag)
        ft.commitAllowingStateLoss()
    }

}